import React from 'react';
import { Form, Input, Button, Icon, message, Select } from 'antd';
import { connect } from 'react-redux';
import * as routerActions from 'react-router-redux';
import Api from 'Utils/api';
import QuestionOption from './Component/QuestionOption';
import CommonBorder from './../../../../DispatchPage/Components/CommonBorder';
import './index.scss';

const FormItem = Form.Item;
const { TextArea } = Input;
const Option = Select.Option;
let option = 1;
const CHARACTER_ARR = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'];
class AddNewQuestion extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      optionArr: [option],
      subjectId: props.params.id,
      loading: false,
      questionType: [],
      id: props.params.id
    };
    this.initData = ::this.initData;
  }
  componentWillMount() {
    this.initData();
  }
  initData() {
    const self = this;
    const api = new Api({
      method: 'GET',
      path: `/subjects/subject_type/${this.state.id}`,
      success: (json) => {
        const res = json && json.length > 0 ? json[0] : {};
        const newquestionType = res.question_type ? res.question_type : [];
        option = 1;
        self.setState({
          questionType: newquestionType,
          optionArr: [option],
        });
      },
      error: (msg) => {
        message.error(msg, 3);
      },
    });
    api.run();
  }
  handleCancel() {
    this.props.dispatch(routerActions.goBack());
  }
  handleSubmit() {
    const { subjectId } = this.state;
    this.props.form.validateFieldsAndScroll((err) => {
      if (!err) {
        const formValue = this.props.form.getFieldsValue();
        // get option component value
        const objValue = Object.values(formValue);
        objValue.shift();
        objValue.shift();
        if (objValue.length < 2) {
          message.warn('备选项最少2个，请添加', 3);
          return;
        }
        if (!objValue[objValue.length - 1]) {
          message.warn('请填写当前选项信息', 3);
          return;
        }
        const allOption = [];
        const selectAnswer = [];
        // get option value arr and answer value arr
        for (let i = 0, len = objValue.length; i < len; i++) {
          allOption.push(objValue[i].sigOption);
          selectAnswer.push(objValue[i].sigCheck);
        }
        // if have a right answer
        if (!(selectAnswer.filter(item => item).length)) {
          message.warn('请设置正确答案', 3);
          return;
        }
        const answer = [];
        for (let i = 0, len = selectAnswer.length; i < len; i++) {
          if (selectAnswer[i]) {
            answer.push(CHARACTER_ARR[i]);
          }
        }
        const data = {
          question: formValue.question,
          all_option: allOption,
          answer: answer,
          question_type: formValue.question_type
        };
        this.setState({ loading: true });
        const api = new Api({
          method: 'POST',
          path: `/choices/admin/${subjectId}`,
          data,
          success: () => {
            this.setState({ loading: false });
            this.props.dispatch(routerActions.goBack());
          },
          error: (msg) => {
            this.setState({ loading: false });
            message.error(msg, 3);
          },
        });
        api.run();
      }
    });
  }
  handleAdd() {
    const { optionArr } = this.state;
    if (optionArr.length === 10) {
      message.warn('最多10个选项', 3);
      return;
    }
    const formValue = this.props.form.getFieldsValue();
    const objValue = Object.values(formValue);
    if (!objValue[objValue.length - 1]) {
      message.warn('请填写当前选项信息', 3);
      return;
    }
    optionArr.push(++option);
    this.setState({
      optionArr: [...optionArr]
    });
  }
  render() {
    const { form } = this.props;
    const { getFieldDecorator } = form;
    const { optionArr, questionType } = this.state;
    return (
      <div>
        <CommonBorder
          title="食安测评试题"
          content={
            <div className="add-new-question-page">
              <Form layout={'horizontal'} className="report-form" >
                <FormItem label="类型">
                  {getFieldDecorator('question_type', {
                    rules: [
                      { required: true, message: '请选择类别' }
                    ]
                  })(
                    <Select placeholder="请选择类别" style={{ width: 840, height: 40 }} >
                      {
                        questionType.map((item) => {
                          return <Option value={item} key={item}>{item}</Option>;
                        })
                      }
                    </Select>
                  )}
                </FormItem>
                <FormItem label="题面">
                  {getFieldDecorator('question', {
                    rules: [
                      { required: true, message: '请输入题面' }
                    ]
                  })(
                    <TextArea placeholder="请输入题面" rows={4} style={{ width: 840, height: 150 }} />
                  )}
                </FormItem>
                <Button className="btn" onClick={this.handleAdd.bind(this)} >
                  <Icon type="plus-circle-o" />
                  添加选项
                </Button>
                {
                  optionArr && optionArr.length > 0 ?
                    optionArr.map(item => (
                      <FormItem label={`备选项${item}`} key={item}>
                        {getFieldDecorator(`option${item}`, {
                        })(
                          <QuestionOption />
                        )}
                      </FormItem>
                    ))
                    : ''
                }
                <div className="btn-wrap">
                  <Button className="cancel-btn" onClick={this.handleCancel.bind(this)}>
                   取消
                  </Button>
                  <Button
                    className="ok-btn"
                    onClick={this.handleSubmit.bind(this)}
                    loading={this.state.loading}
                  >
                    保存
                  </Button>
                </div>
              </Form>
            </div>
          }
        />
      </div>
    );
  }
}
function mapStateToProps(state) {
  return {
    ...state.routing
  };
}

export default Form.create()(connect(mapStateToProps)(AddNewQuestion));
